<template>
  <div>
    <div class="search" ref="search">
      <input type="text" v-model="keyword" class="searchInput" placeholder="请输入城市名称">
    </div>
    <div class="search-content" ref="searchContent" v-show="keyword">
      <ul>
        <li class="" v-for="item of list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li v-show="hasNoData" class="tc">没有搜索到相关数据</li>
      </ul>
    </div>
  </div>
</template>
<script type='text/babel'>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  created () {},
  mounted () {
    this.scroll = new Bscroll(this.$refs.searchContent)
  },
  updated () {},
  methods: {
    handleCityClick (city) {
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    hasNoData () {
      let hasNoData = false
      hasNoData = this.list.length === 0 ? 1 : false
      return hasNoData
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.keyword === '') {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            let name, spell
            name = value.name
            spell = value.spell
            if (name.indexOf(this.keyword) > -1 || spell.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  components: {}
}
</script>
<style scoped lang="scss" rel="stylesheet/scss">
  @import "../../../assets/styles/variable";
  .search{
    height:.80rem;
    padding: 0 .2rem;
    background: $bgColor1;
    .searchInput{
      width:100%;
      height:.56rem;
      margin-top:.07rem;
      border-radius: .06rem;
      background: #fff;
      line-height:.56rem;
      box-sizing: border-box;
      padding: 0 .2rem;
      text-align: center;
      color: #999;
      font-size: 12px;
    }
  }
  .search-content{
    position: fixed;
    top:1.7rem;
    left:0;
    right:0;
    bottom:0;
    z-index: 10;
    background: #fff;
    overflow: hidden;
    ul{
      li{
        line-height:.76rem;
        padding-left:.1rem;
        border-bottom: 1px solid #eaeaea;
      }
      .tc{
        text-align: center;
      }
    }
  }
</style>
